<template>
  <div id="div-main" style="height:100%;background-color:#f3f3f4;">

    
        <el-row ref="rowSearchBar" :gutter="0" style="background-color:white;padding:0px;margin:0px;" v-if="isShowSearchBar">

          <el-form @keyup.enter.native="onSubmit" ref="form-search" :inline="true" :model="formInline" style="position: relative;top:12px;">
            <el-form-item label="食品名称" prop="foodName" style="float:left;margin-left:15px;">
              <el-input v-model="formInline.foodName" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="region" style="float:left;">
                <el-input v-model="formInline.region" placeholder=""></el-input>
              </el-select>
            </el-form-item>
            <el-form-item style="float:left;">
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="resetForm('form-search')">重置</el-button>
            </el-form-item>
          </el-form>

        </el-row>

        <div style="height:10px;width:100%;"></div>
        
       

     <vxe-toolbar print custom style="background-color:white;">
      <template v-slot:buttons>
        &nbsp;&nbsp;&nbsp;
        <el-button size="small" type="primary" @click="operation('add')">新增</el-button>
        <el-button size="small" type="success" @click="operation('edit')" class="button-green">编辑</el-button>
        <el-button size="small" type="warning" @click="operation('remove')" class="button-yellow">删除</el-button>
        <el-button size="small" type="info" @click="operation('import')" class="button-info">导入</el-button>
        <el-button size="small" type="danger" @click="operation('export')" class="button-warning">导出</el-button>
      </template>
      <template v-slot:tools>
        <vxe-button type="text" class="tool-btn" @click="showOrHideSearchBar" style="color:#333;border:1px solid #dcdfe6;padding:9px 10px;">
          <font-awesome-icon :icon="['fas','search']"/>
        </vxe-button>
        <vxe-button type="text" icon="vxe-icon--refresh" class="tool-btn" style="color:#333;border:1px solid #dcdfe6;padding:9px 10px;margin-right:10px;"></vxe-button>
      </template>
    </vxe-toolbar>
    
    <div style="height:calc(100% - 180px);">
      <vxe-table
        border
        show-overflow
        ref="tableMain"
        height="auto"
        row-id="id"
        size="medium"
        :loading="loading"
        :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
        :checkbox-config="{reserve: true}"
        :data="tableData">
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
        <vxe-table-column field="foodName" title="食品名称" sortable></vxe-table-column>
        <vxe-table-column field="imagePath" title="图片"></vxe-table-column>
        <vxe-table-column field="stateName" title="状态"></vxe-table-column>
        <vxe-table-column field="price" title="价格"></vxe-table-column>
        <vxe-table-column title="操作" align="center" sortable>
          <template v-slot="{ row }">
            <!-- <vxe-button status="primary" @click="clickFooterItem()">支持</vxe-button>
            <vxe-button @click="clickFooterItem()">放弃</vxe-button> -->

            <el-button size="mini" type="success" @click="operation('edit')" class="button-green">编辑</el-button>
            <el-button size="mini" type="warning" @click="removeByIds(row.id)" class="button-yellow">删除</el-button>

          </template>
        </vxe-table-column>
      </vxe-table>
    </div>

    <vxe-pager
      perfect
      size="medium"
      :loading="loading"
      :current-page="tablePage.currentPage"
      :page-size="tablePage.pageSize"
      :total="tablePage.totalResult"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
      @page-change="handlePageChange">
    </vxe-pager>


  </div>
</template>

<script>
import form_add from '@/components/add'
import form_edit from '@/components/edit'
export default {
  name: 'table',
  data () {
    return {

      isShowSearchBar:true,//是否显示查询栏

     loading: false,
      tableData: [],
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0
      },

      formInline: {
          foodName: '',
          region: ''
        }

    }
  },
  created () {
    this.findList()
  },
  methods: {
    findList () {
      
      var _this = this;
      _this.loading = true
      _this.$axios({
          method: 'post',
          url: 'http://127.0.0.1:8888/shop/food/test',
          data: _this.$qs.stringify(
            {
              foodName:_this.formInline.foodName,
              pageNum:_this.tablePage.currentPage,
              pageSize:_this.tablePage.pageSize
            }
          )
      })
      .then(function (response) {
           let result = response.data;
           if(result){
             _this.tableData = result.rows;
              _this.tablePage.totalResult  = result.total;
              
           }
           _this.loading = false;
      })
      .catch(function (error) {
        console.log(error);
          _this.loading = false
      });
      
      _this.loading = false
      
    },
    removeByIds(ids){
       let _this = this;


        _this.$layer.confirm('确定要删除选中的数据吗？',{
          title: '提示',
          btn: ['确定', '取消'],
          icon: 3
        },
        layerid => {
          _this.$layer.close(layerid);
          
          
          let loadingId = _this.$layer.loading({});
        
          _this.$axios({
            method: 'post',
            url: 'http://127.0.0.1:8888/shop/food/testRemove',
            data: _this.$qs.stringify(
              {ids:ids}
            )
          })
          .then(function (response) {
              _this.$layer.close(loadingId);
              let result = response.data;
              if(result){
                if(result.code===0){//成功
                    _this.$layer.msg('删除成功');
                    _this.findList();//执行父级页面的刷新
                }else if(result.code===301){//警告
                  _this.$layer.alert("删除成功,但存在警告（"+result.msg+"）",{
                      title: '提示',
                      icon:0  //0,1,2,3
                    },lid => {
                      _this.$layer.close(lid);
                    }
                  );
                }else if(result.code===500){//错误
                _this.$layer.alert("删除失败",{
                      title: '提示',
                      icon:1  //0,1,2,3
                    },lid => {
                      _this.$layer.close(lid);
                    }
                  );

                }
              }
          })
          .catch(function (error) {
            _this.$layer.close(loadingId);
            console.log(error);
          });



        },
        layerid => {
          _this.$layer.close(layerid);
        }
      );




    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.findList()
    },showOrHideSearchBar () {//显示或隐藏查询栏
        this.isShowSearchBar = !this.isShowSearchBar;
    },onSubmit() {
      //查询表单提交
      this.findList();
    },
    resetForm(formName) {//重置
        this.$refs[formName].resetFields();
    },doEdit(rowId){//编辑操作
      _this.$layer.iframe({
        content: {
          content: form_edit,
          parent: _this,
          data: { iframeData: {"rowId":rowId} }
        },
        area: ['900px', '600px'],
        title: '编辑',
        maxmin: true,
        shade: false,
        shadeClose: false,
        cancel: () => { //关闭弹窗事件
        }
      });
    },doRemove(ids){//删除操作

    },operation(type){//表格操作
      var _this = this;
      switch(type) {
          case 'add':

              _this.$layer.iframe({
                content: {
                  content: form_add,
                  parent: _this,
                  data: { iframeData: {} }
                },
                area: ['900px', '600px'],
                title: '添加',
                maxmin: true,
                shade: false,
                shadeClose: false,
                cancel: () => { //关闭弹窗事件
                }
              });

              break;
          case 'edit':
              let selectRecords = this.$refs.tableMain.getCheckboxRecords();
              if(selectRecords.length===0){
                _this.$layer.msg('请先选中要编辑的行数据');
                return;
              }else if(selectRecords.length>1){
                _this.$layer.msg('只能选中一条数据进行编辑');
                return;
              }

              _this.doEdit(selectRecords[0].id);

              break;
          case 'remove':
              let deleteRows = this.$refs.tableMain.getCheckboxRecords();
              if(deleteRows.length===0){
                _this.$layer.msg('请先选中要删除行数据');
                return;
              }

              let ids = "";
              for(var row of deleteRows){
                ids += (row.id+",");
              }
              ids = ids.substring(0,ids.length-1);

              _this.removeByIds(ids);
              
              break;
          case 'import':
         
              break;
          case 'export':
         
              break;
      } 
    }


  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#div-main /deep/ .vxe-button.type--button.is--circle {
    padding: 0 .5em;
    min-width: 34px;
    border-radius: 0;
}

#div-main /deep/ .vxe-toolbar .vxe-custom--wrapper{
  margin-right: 15px;
}

</style>
